<template>
  <el-dialog
    v-model="dialogVisible"
    :title="isEdit ? '编辑角色' : '新增角色'"
    width="800px"
    :close-on-click-modal="false"
    @close="handleClose"
  >
    <el-form
      ref="formRef"
      v-loading="loading"
      :model="formData"
      :rules="formRules"
      label-width="80px"
      class="role-form"
    >
      <!-- 基本信息区域 -->
      <div class="form-basic-info">
        <el-form-item label="角色标识" prop="roleKey">
          <el-input
            v-model="formData.roleKey"
            placeholder="请输入角色标识"
            :disabled="isEdit"
            maxlength="50"
            show-word-limit
          />
          <div class="form-tip">
            角色标识只能包含字母、数字和下划线，创建后不可修改
          </div>
        </el-form-item>

        <el-form-item label="角色名称" prop="roleName">
          <el-input
            v-model="formData.roleName"
            placeholder="请输入角色名称"
            maxlength="100"
            show-word-limit
          />
        </el-form-item>

        <el-form-item label="角色描述" prop="description">
          <el-input
            v-model="formData.description"
            type="textarea"
            placeholder="请输入角色描述"
            :rows="3"
            maxlength="500"
            show-word-limit
          />
        </el-form-item>

        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="formData.status">
            <el-radio :value="'0'">正常</el-radio>
            <el-radio :value="'1'">停用</el-radio>
          </el-radio-group>
        </el-form-item>
      </div>

      <!-- 权限分配区域 -->
      <div class="permission-section">
        <div class="permission-section-title">
          <h4>权限分配</h4>
          <span class="permission-count">
            已选择 {{ formData.permissionIds?.length || 0 }} /
            {{ permissionList.length }} 个权限
          </span>
        </div>

        <div class="permission-container">
          <div class="permission-header">
            <div class="permission-controls">
              <el-checkbox
                v-model="selectAll"
                :indeterminate="isIndeterminate"
                @change="handleSelectAll"
              >
                全选权限
              </el-checkbox>
              <el-input
                v-model="searchKeyword"
                placeholder="搜索权限..."
                size="small"
                style="width: 200px"
                clearable
              >
                <template #prefix>
                  <IconifyIconOffline icon="ep:search" />
                </template>
              </el-input>
            </div>
          </div>

          <div v-loading="permissionLoading" class="permission-list">
            <el-checkbox-group v-model="formData.permissionIds">
              <div class="permission-grid">
                <div
                  v-for="permission in filteredPermissionList"
                  :key="permission.id"
                  class="permission-item"
                >
                  <el-checkbox
                    :value="permission.id"
                    class="permission-checkbox"
                  >
                    <div class="permission-card">
                      <!-- 权限名称 -->
                      <div class="permission-title">
                        {{ permission.permName }}
                      </div>

                      <!-- 权限标识 -->
                      <div class="permission-key">
                        <el-tag size="small" type="info" effect="plain">
                          {{ permission.permKey }}
                        </el-tag>
                      </div>

                      <!-- 权限描述 -->
                      <div
                        v-if="permission.description"
                        class="permission-description"
                      >
                        {{ permission.description }}
                      </div>
                    </div>
                  </el-checkbox>
                </div>
              </div>
            </el-checkbox-group>

            <!-- 空状态 -->
            <el-empty
              v-if="!filteredPermissionList.length && !permissionLoading"
              description="没有找到匹配的权限"
              :image-size="80"
            />
          </div>
        </div>
      </div>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" :loading="saving" @click="handleSubmit">
          {{ isEdit ? "更新" : "创建" }}
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch } from "vue";
import { ElMessage } from "element-plus";
import { IconifyIconOffline } from "@/components/ReIcon";
import {
  createRoleApi,
  updateRoleApi,
  checkRoleKeyApi,
  getAllPermissionsApi,
  RoleManagementUtils,
  type RoleInfo,
  type PermissionInfo,
  type CreateRoleParams,
  type UpdateRoleParams
} from "@/api/role-management";

interface Props {
  visible: boolean;
  roleInfo?: RoleInfo | null;
}

interface Emits {
  (e: "update:visible", value: boolean): void;
  (e: "success"): void;
}

const props = defineProps<Props>();
const emit = defineEmits<Emits>();

// 响应式数据
const dialogVisible = ref(false);
const loading = ref(false);
const saving = ref(false);
const permissionLoading = ref(false);
const formRef = ref();
const permissionList = ref<PermissionInfo[]>([]);
const selectAll = ref(false);
const searchKeyword = ref("");

// 表单数据
const formData = reactive<CreateRoleParams & { id?: number }>({
  roleKey: "",
  roleName: "",
  description: "",
  status: "0",
  permissionIds: []
});

// 计算属性
const isEdit = computed(() => !!props.roleInfo?.id);

const isIndeterminate = computed(() => {
  const selectedCount = formData.permissionIds?.length || 0;
  const totalCount = filteredPermissionList.value.length;
  return selectedCount > 0 && selectedCount < totalCount;
});

const filteredPermissionList = computed(() => {
  if (!searchKeyword.value) {
    return permissionList.value;
  }
  const keyword = searchKeyword.value.toLowerCase();
  return permissionList.value.filter(
    permission =>
      permission.permName.toLowerCase().includes(keyword) ||
      permission.permKey.toLowerCase().includes(keyword) ||
      (permission.description &&
        permission.description.toLowerCase().includes(keyword))
  );
});

// 表单验证规则
const formRules = {
  roleKey: [
    { required: true, message: "请输入角色标识", trigger: "blur" },
    { min: 2, max: 50, message: "角色标识长度为2-50个字符", trigger: "blur" },
    {
      pattern: /^[a-zA-Z0-9_]+$/,
      message: "角色标识只能包含字母、数字和下划线",
      trigger: "blur"
    },
    { validator: validateRoleKey, trigger: "blur" }
  ],
  roleName: [
    { required: true, message: "请输入角色名称", trigger: "blur" },
    { min: 2, max: 100, message: "角色名称长度为2-100个字符", trigger: "blur" }
  ],
  description: [
    { max: 500, message: "角色描述最多500个字符", trigger: "blur" }
  ],
  status: [{ required: true, message: "请选择状态", trigger: "change" }]
};

// 自定义验证器
function validateRoleKey(_rule: any, value: string, callback: any) {
  if (!value) {
    callback();
    return;
  }

  if (!RoleManagementUtils.validateRoleKey(value)) {
    callback(new Error("角色标识格式不正确"));
    return;
  }

  // 异步验证
  checkRoleKeyApi(value, isEdit.value ? props.roleInfo?.id : undefined)
    .then(response => {
      if (response.code === 200) {
        if (response.data === false) {
          callback(new Error("角色标识已存在"));
        } else {
          callback();
        }
      } else {
        callback(new Error("验证角色标识失败"));
      }
    })
    .catch(() => {
      callback(new Error("验证角色标识失败"));
    });
}

// 监听visible变化
watch(
  () => props.visible,
  val => {
    dialogVisible.value = val;
    if (val) {
      loadPermissions();
      if (props.roleInfo) {
        loadRoleData();
      } else {
        resetForm();
      }
    }
  },
  { immediate: true }
);

// 监听权限选择变化
watch(
  () => formData.permissionIds,
  newVal => {
    const selectedCount = newVal?.length || 0;
    const totalCount = permissionList.value.length;
    selectAll.value = selectedCount === totalCount && totalCount > 0;
  },
  { deep: true }
);

/**
 * 加载权限列表
 */
const loadPermissions = async () => {
  try {
    permissionLoading.value = true;
    const response = await getAllPermissionsApi();
    if (response.code === 200 && response.data) {
      permissionList.value = response.data;
    } else {
      ElMessage.error(response.message || "获取权限列表失败");
    }
  } catch (error) {
    console.error("加载权限列表失败:", error);
    ElMessage.error("获取权限列表失败");
  } finally {
    permissionLoading.value = false;
  }
};

/**
 * 加载角色数据（编辑模式）
 */
const loadRoleData = () => {
  if (!props.roleInfo) return;

  Object.assign(formData, {
    id: props.roleInfo.id,
    roleKey: props.roleInfo.roleKey,
    roleName: props.roleInfo.roleName,
    description: props.roleInfo.description || "",
    status: props.roleInfo.status,
    permissionIds: RoleManagementUtils.extractPermissionIds(
      props.roleInfo.permissions || []
    )
  });
};

/**
 * 重置表单
 */
const resetForm = () => {
  Object.assign(formData, {
    id: undefined,
    roleKey: "",
    roleName: "",
    description: "",
    status: "0",
    permissionIds: []
  });
  formRef.value?.clearValidate();
  selectAll.value = false;
};

/**
 * 全选/取消全选
 */
const handleSelectAll = (checked: boolean) => {
  if (checked) {
    // 全选当前筛选结果中的权限
    const filteredIds = RoleManagementUtils.extractPermissionIds(
      filteredPermissionList.value
    );
    const currentIds = formData.permissionIds || [];
    // 合并已选择的权限和当前筛选结果
    const allIds = [...new Set([...currentIds, ...filteredIds])];
    formData.permissionIds = allIds;
  } else {
    // 取消选择当前筛选结果中的权限
    const filteredIds = RoleManagementUtils.extractPermissionIds(
      filteredPermissionList.value
    );
    formData.permissionIds = (formData.permissionIds || []).filter(
      id => !filteredIds.includes(id)
    );
  }
};

/**
 * 提交表单
 */
const handleSubmit = async () => {
  try {
    await formRef.value?.validate();

    saving.value = true;

    if (isEdit.value) {
      // 编辑模式
      const params: UpdateRoleParams = {
        roleName: formData.roleName,
        description: formData.description,
        status: formData.status,
        permissionIds: formData.permissionIds
      };

      const response = await updateRoleApi(formData.id!, params);
      if (response.code === 200) {
        ElMessage.success("角色更新成功");
        emit("success");
        handleClose();
      } else {
        ElMessage.error(response.message || "角色更新失败");
      }
    } else {
      // 新增模式
      const params: CreateRoleParams = {
        roleKey: formData.roleKey,
        roleName: formData.roleName,
        description: formData.description,
        status: formData.status,
        permissionIds: formData.permissionIds
      };

      const response = await createRoleApi(params);
      if (response.code === 200) {
        ElMessage.success("角色创建成功");
        emit("success");
        handleClose();
      } else {
        ElMessage.error(response.message || "角色创建失败");
      }
    }
  } catch (error) {
    if (error !== false) {
      // 表单验证失败时error为false
      console.error("提交角色失败:", error);
      ElMessage.error(isEdit.value ? "角色更新失败" : "角色创建失败");
    }
  } finally {
    saving.value = false;
  }
};

/**
 * 关闭对话框
 */
const handleClose = () => {
  emit("update:visible", false);
};
</script>

<style lang="scss" scoped>
// 响应式设计
@media (width <= 768px) {
  :deep(.el-dialog) {
    width: 95% !important;
    margin: 5vh auto !important;
  }

  .form-basic-info {
    grid-template-columns: 1fr;
    gap: 16px;

    :deep(.el-form-item) {
      flex-direction: column;
      align-items: stretch;

      .el-form-item__label {
        width: auto !important;
        height: auto;
        padding-right: 0;
        padding-bottom: 4px;
        line-height: 1.5;
        text-align: left;
      }

      .el-form-item__content {
        width: 100%;
      }

      &:nth-child(3),
      &:nth-child(4) {
        grid-column: 1;
      }
    }
  }

  .permission-section {
    .permission-section-title {
      flex-direction: column;
      gap: 8px;
      align-items: flex-start;
    }
  }

  .permission-container {
    .permission-header {
      .permission-controls {
        flex-direction: column;
        gap: 12px;

        .el-input {
          width: 100% !important;
        }
      }
    }

    .permission-list {
      max-height: 300px;

      .permission-grid {
        grid-template-columns: 1fr;
        gap: 16px;
        padding: 8px;
      }

      .permission-item {
        .permission-card {
          min-height: 120px;
          padding: 16px;

          .permission-title {
            font-size: 15px;
          }
        }
      }
    }
  }
}

.role-form {
  display: flex;
  flex-direction: column;
  gap: 20px;

  // 确保表单在不同状态下的对齐
  :deep(.el-form-item) {
    &.is-error {
      .el-form-item__label {
        line-height: 32px;
      }
    }
  }
}

.form-basic-info {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 20px;
  align-items: start;

  :deep(.el-form-item) {
    display: flex;
    align-items: flex-start;
    margin-bottom: 0;

    .el-form-item__label {
      display: flex;
      flex-shrink: 0;
      align-items: center;
      justify-content: flex-end;
      width: 80px !important;
      height: 32px;
      padding-right: 12px;
      line-height: 32px;
      text-align: right;
    }

    .el-form-item__content {
      flex: 1;
      min-width: 0;
    }

    &:nth-child(3) {
      grid-column: 1 / -1; // 描述字段占满整行
    }

    &:nth-child(4) {
      grid-column: 1 / -1; // 状态字段占满整行
    }
  }
}

.form-tip {
  margin-top: 4px;
  font-size: 12px;
  line-height: 1.4;
  color: #909399;
}

.permission-section {
  .permission-section-title {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding-bottom: 12px;
    margin-bottom: 16px;
    border-bottom: 2px solid #e4e7ed;

    h4 {
      margin: 0;
      font-size: 16px;
      font-weight: 600;
      color: #303133;
    }

    .permission-count {
      padding: 6px 12px;
      font-size: 12px;
      font-weight: 500;
      color: #909399;
      background-color: #e9ecef;
      border-radius: 16px;
    }
  }
}

.permission-container {
  background-color: #fff;
  border: 1px solid #dcdfe6;
  border-radius: 8px;

  .permission-header {
    padding: 16px;
    background-color: #f8f9fa;
    border-bottom: 1px solid #e4e7ed;
    border-radius: 8px 8px 0 0;

    .permission-controls {
      display: flex;
      gap: 16px;
      align-items: center;
      justify-content: space-between;
    }
  }

  .permission-list {
    max-height: 450px;
    padding: 16px;
    overflow-y: auto;

    .permission-grid {
      display: grid;
      grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
      gap: 20px;
      padding: 12px;
    }

    .permission-item {
      position: relative;
      overflow: hidden;
      background: linear-gradient(135deg, #fff 0%, #f8fafc 100%);
      border: 2px solid #e2e8f0;
      border-radius: 12px;
      box-shadow: 0 2px 8px rgb(0 0 0 / 6%);
      transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);

      &:hover {
        border-color: #409eff;
        box-shadow: 0 8px 25px rgb(64 158 255 / 15%);
        transform: translateY(-4px);
      }

      .permission-card {
        position: relative;
        display: flex;
        flex-direction: column;
        height: 100%;
        min-height: 140px;
        padding: 20px;
        padding-top: 60px;

        .permission-title {
          position: absolute;
          top: 20px;
          left: 50%;
          z-index: 1;
          width: calc(100% - 40px);
          margin-bottom: 12px;
          font-size: 16px;
          font-weight: 600;
          line-height: 1.4;
          color: #1a202c;
          text-align: center;
          word-break: break-word;
          transform: translateX(-50%);
        }

        .permission-key {
          display: flex;
          justify-content: center;
          margin-top: 0;
          margin-bottom: 16px;

          .el-tag {
            padding: 4px 8px;
            font-family: Monaco, Menlo, "Ubuntu Mono", monospace;
            font-size: 11px;
            font-weight: 500;
            border-radius: 6px;
          }
        }

        .permission-description {
          flex: 1;
          padding: 12px 16px;
          margin-top: auto;
          font-size: 13px;
          line-height: 1.6;
          color: #64748b;
          text-align: center;
          word-break: break-word;
          background: rgb(248 250 252 / 80%);
          border: 1px solid rgb(226 232 240 / 60%);
          border-radius: 8px;
          backdrop-filter: blur(10px);
        }
      }
    }
  }
}

.dialog-footer {
  text-align: right;
}

// 自定义滚动条样式
.permission-list::-webkit-scrollbar {
  width: 6px;
}

.permission-list::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

.permission-list::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;

  &:hover {
    background: #a8a8a8;
  }
}

// 复选框组样式优化
:deep(.el-checkbox-group) {
  width: 100%;

  .permission-checkbox {
    display: block;
    width: 100%;
    height: 100%;
    margin: 0;

    .el-checkbox__input {
      position: absolute;
      top: 16px;
      left: 16px;
      z-index: 20;

      .el-checkbox__inner {
        width: 18px;
        height: 18px;
        background-color: #fff;
        border: 2px solid #d1d5db;
        border-radius: 6px;
        transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);

        &:hover {
          border-color: #409eff;
          transform: scale(1.1);
        }
      }
    }

    .el-checkbox__label {
      display: block;
      width: 100%;
      height: 100%;
      padding: 0;
    }

    &.is-checked {
      .el-checkbox__input .el-checkbox__inner {
        background-color: #409eff;
        border-color: #409eff;

        &::after {
          border-color: #fff;
          border-width: 2px;
        }
      }
    }
  }
}

// 表单项样式优化
:deep(.el-form-item) {
  .el-form-item__label {
    font-weight: 600;
    color: #303133;
  }

  .el-form-item__content {
    .el-input__count {
      font-size: 12px;
      color: #909399;
    }

    .el-input,
    .el-textarea,
    .el-radio-group {
      width: 100%;
    }

    .el-input__wrapper {
      min-height: 32px;
    }
  }
}

// 重复的选择器已合并到上面的 .role-form 中
</style>
